package com.example.erhuo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.erhuo.LikeInformation;
import com.example.erhuo.R;
import com.example.erhuo.adapter.LikeAdapter;
import com.example.erhuo.adapter.WantAdapter;
import com.example.erhuo.api.NetAPI;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.LinkedList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class WantMeActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private static String TAG = "WantMeActivity";

    private ListView listView;
    private WantAdapter wantAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.title_layout);
            TextView textView = (TextView) actionBar.getCustomView().findViewById(R.id.display_title);
            textView.setText("想要我的");
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
        }
        setContentView(R.layout.activity_want_me);

        initActivity();
        getAllLikes();
    }

    private void initActivity() {
        listView = findViewById(R.id.want_listview);
        listView.setOnItemClickListener(this);
        wantAdapter = new WantAdapter(new LinkedList<LikeInformation>(), WantMeActivity.this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void getAllLikes() {
        Callback callback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "获取订单失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "获取订单失败，请检查网络", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String information = response.body().string();
                Log.i(TAG, information);
                JSONObject json;
                try {
                    json = new JSONObject(information);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    switch (msg) {
                        case "查询成功": {
                            JSONArray dataJson = json.getJSONObject("data").getJSONArray("sellingList");
                            for (int i = 0; i < dataJson.length(); i++) {
                                JSONObject object = dataJson.getJSONObject(i);
                                String orderId = object.getString("orderid");
                                String solderId = object.getString("solderid");
                                String buyerId = object.getString("buyerid");
                                String price = object.getString("price");
                                String orderStatus = object.getString("orderstatus");
                                String goodId = object.getString("goodid");
                                LikeInformation like = new LikeInformation(orderId, solderId, buyerId, price, orderStatus, goodId);
                                RequestBody body = new FormBody.Builder()
                                        .add("goodid", goodId)
                                        .build();
                                Callback callback1 = new Callback() {
                                    @Override
                                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                        Log.e(TAG, "获取想要的具体信息失败");
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(getApplicationContext(), "获取想要的具体信息失败，请检查网络", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }

                                    @Override
                                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                                        String information = response.body().string();
                                        dealGoodDetail(information, like);
                                    }
                                };
                                NetAPI.postJsonWithToken("api/GoodOper/searchGoodWithId/", body, callback1, MainActivity.token);
                                try {
                                    Thread.sleep(200);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                wantAdapter.addLike(like);
                            }
                            Log.i(TAG, "增加了" + dataJson.length());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    listView.setAdapter(wantAdapter);
                                }
                            });

                            break;
                        }
                        default: {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), "获取信息失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        NetAPI.get("api/OrderOper/getMySellingOrder/", callback, MainActivity.token);
    }

    public void dealGoodDetail(String information, LikeInformation like) {
        JSONObject object;
        //Log.i(TAG, information);
        try {
            object = new JSONObject(information);
            JSONObject jsonObject = new JSONObject(object.getString("data"));
            JSONObject object1 = new JSONObject(jsonObject.getString("good"));
            String title = object1.getString("goodname");
            String imagePath = object1.getString("imagePATH");
            like.setTitle(title);
            Callback callback = new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    like.setImage(null);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    byte[] bytes = response.body().bytes();
                    Bitmap image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    like.setImage(image);
                }
            };
            NetAPI.get("api/download/?path=" + imagePath, callback, "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Toast.makeText(MyLikeActivity.this, "你点击了第" + position + "项", Toast.LENGTH_SHORT).show();
        LikeInformation like = (LikeInformation) wantAdapter.getItem(position);
        Log.i(TAG, "你点击了第" + position + "项");
        Log.i(TAG, "status 是 " + like.getOrderStatus());
        if (like.getOrderStatus().equals("1")) {
            //报价
            AlertDialog.Builder builder = new AlertDialog.Builder(WantMeActivity.this);
            builder.setTitle("是否接受报价？");
            builder.setNeutralButton("取消", null);
            builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.setPositiveButton("接受",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String orderId = like.getOrderId();
                            RequestBody body = new FormBody.Builder()
                                    .add("orderid", orderId)
                                    .build();
                            Callback callback = new Callback() {
                                @Override
                                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                    Log.e(TAG, "报价失败");
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), "报价失败", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }

                                @Override
                                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                                    String information = response.body().string();
                                    JSONObject object;
                                    try {
                                        object = new JSONObject(information);
                                        String code = object.getString("code");
                                        String msg = object.getString("msg");
                                        switch (code) {
                                            case "200": {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(getApplicationContext(), "确认成功", Toast.LENGTH_SHORT).show();
                                                        wantAdapter.removeAll();
                                                        getAllLikes();
                                                    }
                                                });
                                                break;
                                            }
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            };
                            NetAPI.postJsonWithToken("api/OrderOper/confirm/", body, callback, MainActivity.token);
                        }
                    });
            builder.show();
        }
    }
}